<?php
/**
 * Created by PhpStorm.
 * User: caicm
 * Date: 2017/2/28
 * Time: 10:40
 */

namespace SDXApi\Service;


class LouxiaoerService {

    /*
     * 订单绑定楼小二
     * Created By caicm
     * @param int $order_id
     * return mixed
     */
    public function order_binding_louxiaoer($order_id){
        $louxiaoer_order = D('LouxiaoerOrder')->getLouxiaoerOrderByOrderId($order_id);
        if($louxiaoer_order){
            return '已绑定楼小二';
        }

        //获取订单信息
        $data = M('order_info')->field('sign_building,address,wdr_id as region_id,order_id,address_id,user_id')->find($order_id);
        if(!$data){
            return '未找到订单数据';
        }

        //获取当前订单地标（没有地标以地址作地标）
        $sign_building = $data['sign_building'] ? $data['sign_building'] : $data['address'];

        //根据地标、区域查询楼小二
        $landmark = D('LouxiaoerLandmark')->findLouxiaoerByLandmark($sign_building, $data['region_id']);

        $data['id'] = $landmark['id'];
        $data['louxiaoer_id'] = $landmark['louxiaoer_id'];
        $data['name'] = $landmark['name'];
        $data['phone'] = $landmark['phone'];


        //未找到相应地标
        if(!$data['id']){

            if(!$data['region_id']){
                return '订单没有区域信息';
            }

            //获取地标，没有地标用地址
            $landmark = D('LouxiaoerLandmark')->findLandmarkByName($sign_building, $data['region_id']);

            if($landmark){
                $data['id'] = $landmark['id'];
            }else{
                //写入地标（地点地址）
                $data['id'] = D('LouxiaoerLandmark')->addLandmark($sign_building, $data['region_id']);
            }

        }

        $louxiaoer_user_id = 0;
        $is_first = 0;
        $louxiaoer = array();
        if($data['louxiaoer_id']){
            $binding_louxiaoer_time = time()-28800;
            $created = '系统分配';

            //添加楼小二用户
            $louxiaoer = D('LouxiaoerUser')->findLouxiaoerUser($data['louxiaoer_id'], $data['user_id'], $data['address_id']);
            if(!$louxiaoer){
                $louxiaoer_user_id = D('LouxiaoerUser')->addLouxiaoerUser($data['louxiaoer_id'], $data['user_id'], $data['address_id'], $data['id']);
            }else{
                $louxiaoer_user_id = $louxiaoer['id'];
                $is_first = 1; //首单
            }

        }else{
            $binding_louxiaoer_time = 0;
            $created = '';
        }

        $data['louxiaoer_id'] = $data['louxiaoer_id'] ? $data['louxiaoer_id'] : 0;

        //订单绑定楼小二
        D('LouxiaoerOrder')->orderBindingLouxiaoer($louxiaoer_user_id, $data['user_id'], $data['address_id'], $data['id'], $data['order_id'], $data['louxiaoer_id'], $binding_louxiaoer_time, $created, $is_first);

        return array(
            'name' => $data['name'],
            'phone' => $data['phone']
        );
    }
}